package com.eclipse.organigram.views.ui;

import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;

import com.eclipse.organigram.Activator;
import com.eclipse.organigram.model.entities.Category;
import com.eclipse.organigram.model.entities.Column;
import com.eclipse.organigram.model.entities.Person;
import com.eclipse.organigram.style.Icons;

public class OrganigramColumnLabelProvider extends StyledCellLabelProvider {

	private Column column;
	private int columnIndex;

	public OrganigramColumnLabelProvider(Column column, int columnIndex) {
		this.column = column;
		this.columnIndex = columnIndex;
	}
	
	@Override
	public void update(ViewerCell cell) {
		super.update(cell);
		Object element = cell.getElement();
		
		StyledString styledString = getCellText(element);
		
		cell.setStyleRanges(styledString.getStyleRanges());
		cell.setText(styledString.toString());
		cell.setImage(getImage(element));
	}

	private StyledString getCellText(Object element) {
		StyledString styledString = new StyledString();
		styledString.append(getText(element));
		
		if (isFirstColumn() && element instanceof Category) {
			styledString.append(" (" + ((Category) element).countPersons() + ")", StyledString.QUALIFIER_STYLER);
		}
		return styledString;
	}

	public String getText(Object element) {
		String text = null;
		if (element instanceof Person) {
			text = ((Person) element).getPerson().get(column.getId());
		} 
		else if (isFirstColumn() && element instanceof Category) {
			text = ((Category) element).getName();
		}
		return text == null ? "" : text;
	}
	
	public Image getImage(Object element) {
		if (isFirstColumn()) {
			if (element instanceof Category) {
				return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
			}
			return Activator.getDefault().getImageRegistry().get(Icons.TEAM_MEMBER.name());
		}
		return null;
	}
	
	private boolean isFirstColumn() {
		return columnIndex == 0;
	}
	
}
